<template>
<!-- 点赞组件 -->
  <van-icon
    :name="articleLike === 1 ? 'good-job' : 'good-job-o'"
    :color="articleLike === 1 ? '#e5645f' : ''"
    :loading="followLoading"
    @click="LikeFN"
  />
</template>

<script>
import { likeArticle, dlLikeArticle } from '@/api/article'
export default {
  name: 'LikeArticle',
  data() {
    return {
      followLoading: false // loading 状态显示与否
    }
  },
  // 自定义 v-model 的数据名称
  model: {
    prop: 'articleLike', // 默认是 value
    event: 'update-like' // 默认是 input
  },
  props: {
    // 文章Id
    articleId: {
      type: [Number, String, Object],
      required: true
    },
    // 文章点赞状态
    articleLike: {
      type: Number,
      required: true
    }
  },

  methods: {
    // 点赞和取消点赞
    async LikeFN() {
      this.followLoading = true
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '操作中...',
        forbidClick: true // 是否禁止背景点击
      })

      try {
        let status = 0
        if (this.articleLike === 1) {
          // 已点赞，取消点赞
          await dlLikeArticle(this.articleId)
          // console.log('执行取消点赞')
          status = -1
        } else {
          // 没有点赞，添加点赞
          await likeArticle(this.articleId)
          // console.log('执行添加点赞')
          // console.log(this.articleLike)
          status = 1
        }
        // 更新视图
        this.$emit('update-like', status)
        this.$toast.success(status === 1 ? '点赞成功' : '取消点赞')
      } catch (error) {
        this.$toast('操作失败')
      }
      this.followLoading = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
